import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建用户相关的 axios 实例
const userApi = axios.create({
  baseURL: '/api/users',
  withCredentials: true
})

// 创建聊天相关的 axios 实例
const chatApi = axios.create({
  baseURL: '/v1',
  withCredentials: true
})

// 聊天 API 的请求拦截器
chatApi.interceptors.request.use(
  config => {
    if (!config.url.includes('/login')) {
      config.headers.Authorization = `Bearer ${import.meta.env.VITE_API_KEY}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 聊天 API 的响应拦截器
chatApi.interceptors.response.use(
  response => response.data,
  error => {
    ElMessage.error(error.response?.data?.message || '请求失败')
    return Promise.reject(error)
  }
)

// 获取当前用户信息
const getCurrentUser = () => {
  const userStr = localStorage.getItem('user')
  return userStr ? JSON.parse(userStr) : null
}

// 用户相关的 API
export const login = (username, password) => {
  return userApi.post('/login', { username, password })
}

export const register = (username, password) => {
  return userApi.post('/register', { username, password })
}

export const logout = () => {
  return userApi.post('/logout')
}

// 聊天相关的 API
export const sendMessage = (data) => {
  const user = getCurrentUser()
  return new Promise((resolve, reject) => {
    fetch('/v1/chat-messages', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_API_KEY}`
      },
      body: JSON.stringify({
        ...data,
        user: user?.username  // 使用存储的用户名
      }),
      credentials: 'include'
    }).then(response => {
      const reader = response.body.getReader()
      let fullResponse = ''
      let responseData = null

      function readStream() {
        reader.read().then(({done, value}) => {
          if (done) {
            resolve({ message: fullResponse, ...responseData })
            return
          }

          const chunk = new TextDecoder().decode(value)
          const lines = chunk.split('\n')
          
          lines.forEach(line => {
            if (line.trim() && !line.includes('event: ping')) {
              try {
                if (line.startsWith('data: ')) {
                  const jsonData = JSON.parse(line.slice(6))
                  if (jsonData.event === 'message' && jsonData.answer) {
                    // 更新完整响应
                    fullResponse += jsonData.answer
                    // 更新流式消息
                    if (data.callback) {
                      data.callback(fullResponse)
                    }
                    // 保存会话ID和消息ID
                    if (jsonData.conversation_id) {
                      responseData = {
                        conversation_id: jsonData.conversation_id,
                        message_id: jsonData.message_id
                      }
                    }
                  }
                }
              } catch (error) {
                console.error('解析消息失败:', error, line)
              }
            }
          })

          readStream()
        }).catch(error => {
          reject(error)
        })
      }

      readStream()
    }).catch(error => {
      reject(error)
    })
  })
}

export const getConversations = () => {
  const user = getCurrentUser()
  return chatApi.get('/conversations', {
    params: {
      user: user?.username  // 使用存储的用户名
    }
  })
}

export const getMessages = (conversationId) => {
  const user = getCurrentUser()
  return chatApi.get('/messages', { 
    params: { 
      conversation_id: conversationId,
      user: user?.username  // 使用存储的用户名
    } 
  })
}

export const renameConversation = (conversationId, data) => {
  const user = getCurrentUser()
  return chatApi.post(`/conversations/${conversationId}/name`, {
    ...data,
    user: user?.username  // 使用存储的用户名
  })
}

export const sendFeedback = (messageId, rating, content) => {
  const user = getCurrentUser()
  return chatApi.post(`/messages/${messageId}/feedbacks`, {
    rating,  // 'like', 'dislike', 或 null
    user: user?.username,
    content  // 添加消息内容
  })
}

export const uploadFile = (formData) => {
  return chatApi.post('/files/upload', formData)
}

export const getParameters = () => {
  return chatApi.get('/parameters')
}

// 修改删除会话的 API 方法
export const deleteConversation = (conversationId) => {
  const user = getCurrentUser()
  return chatApi.delete(`/conversations/${conversationId}`, {
    headers: {
      'Content-Type': 'application/json'
    },
    data: {
      user: user?.username  // 使用存储的用户名
    }
  })
} 